var sys = require("sys");

function respond(code, data, res) {
    var payload = JSON.stringify(data);

    res.writeHead(code, {
        "Content-Type": "application/json",
        "Content-Length": payload.length
    });

    res.write(payload);
    res.end();
}

module.exports = {
    create: function (req, res) {
        var self = this;
        var data = "";

        req.on("data", function (chunk) {
            data += chunk;
        });

        req.on("end", function () {
            var sanitized = decodeURIComponent(data.substr(5).replace(/\+/g, " "));

            self.list.add(sanitized, function (item) {
                respond(200, item, res);
            });
        });
    },

    index: function (req, res) {
        this.list.all(function (items) {
            respond(200, items, res);
        });
    },

    update: function (req, res) {
        var match = req.url.match(/(\d+)$/);

        if (!match) {
            return respond(500, {message: "Missing id"}, res);
        }

        this.list.complete(match[1], function (items, err) {
            if (items) {
                respond(200, items, res);
            } else {
                respond(404, {message: err.message}, res);
            }
        });
    }
};
